<template>
  <div class="pad-20 bgc-default">
    <div class="pad-20 bg-color-white">
      <div class="pad-20">
        <span style="color: #333;font-size: 1.5em;font-weight: bold;margin-right:50px;">批量导入商品</span>
        <el-button @click="downloadImportTemplateFile()">下载导入模板</el-button>
        <el-button @click="handleImportRecord()">查看导入历史</el-button>
      </div>
      <el-form ref="form" :model="importEntity" :rules="rules" label-position="right" label-width="150px"
        style='margin-left:50px;'>
       <!-- <el-form-item label="商品导入模板：">
          <span style="font-size: 14px;margin-left: 20px;color: #409eff;cursor: pointer;"
            @click="downloadImportTemplateFile">下载模板</span>
        </el-form-item> -->
        <!-- <el-form-item label="商品图片：">
          <span style="font-size: 14px;margin-left: 20px;color: #409eff;cursor: pointer;"
            @click="handleUploadImage">上传图片</span>
          <div>
            <span style="font-size: 14px; color: #7f7f7f">如需设置商品图片，需先上传图片，再在文件表格中填入对应的商品图片名称，最多上传3000张（超出时上传失败）</span>
          </div>
        </el-form-item> -->
        <el-form-item label="上传文件：" prop="fileUrl">
          <el-upload v-if="!importEntity.fileName" list-type="text" action="/api/common/uploadFiles" accept=".xlsx,.xls"
            name="files" multiple :data="token" :show-file-list="false" v-loading="shareFileLoading"
            :on-success="handleUploadFileUrlSuccess" :before-upload="beforeFileUpload">
            <span style="font-size: 14px;margin-left: 20px;color: #409eff;cursor: pointer;">添加文件</span>
          </el-upload>
          <div v-if="importEntity.fileName">
            <span>{{importEntity.fileName}}</span>
            <span style="font-size: 14px;margin-left: 20px;color: #409eff;cursor: pointer;"
              @click="handleDeleteFile">删除</span>
          </div>
          <div>
            <span style="font-size: 14px; color: #7f7f7f">一次最多导入2000条数据，超出时请分批导入</span>
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveImportGoods">确认</el-button>
        <el-button @click="handleReportCenter" v-if="isImportGoodsSuccess">跳转报表中心查看</el-button>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    importGoods
  } from '@/api/goods/goods'
  import {
    getToken
  } from '@/utils/auth'
  import {
    jumpToReportCenter,
    downloadFile
  } from '@/api/common/common'
  export default {
    data() {
      return {
        shareFileLoading: false,
        importEntity: {
          skuFlag: 0,
          fileName: '',
          fileUrl: ''
        },
        // 是否导入商品成功
        isImportGoodsSuccess: false,
        rules: {
          fileUrl: [{
            required: true,
            message: '请上传要导入的商品',
            trigger: 'change'
          }]
        }
      }
    },
    created() {
      this.token = {
        accessToken: getToken()
      }
    },
    methods: {
      handleImportRecord() {
        var options = {
          reportCenterType: 2,
          reportDataType: 1
        }
        this.handleReportCenter(options)
      },
      // 下载导入商品模板
      downloadImportTemplateFile() {
        var fileName = '批量导入商品模板'
        var fileUrl = 'https://img-1.joinsun.vip/upload/f067f7ff5df07e9c37ebda3ac9c8fc45.xlsx'
        if (this.getSupplierId()) {
          fileName = '供应商-' + fileName
          fileUrl = 'https://img-1.joinsun.vip/upload/f5dc81ea6d222e948157f3d0750d4914.xlsx'
        }
        const options = {}
        downloadFile(fileUrl, options, fileName)
      },
      // 上传图片
      handleUploadImage() {},
      // 删除上传文件
      handleDeleteFile() {
        this.importEntity.fileName = ''
        this.importEntity.fileUrl = ''
      },
      beforeFileUpload(file) {
        console.log(file)
        var fileName = file.name
        if (!fileName) {
          this.$message({
            type: 'error',
            message: '获取不到上传文件名称!'
          })
        }
        var ext = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length)
        const isCanUpload = ext === 'xlsx' || ext === 'xls'
        if (!isCanUpload) {
          this.$message({
            type: 'error',
            message: '上传文件必须是xlsx/xls 格式!'
          })
          return false
        }
        this.shareFileLoading = true

        return (isCanUpload)
      },
      handleUploadFileUrlSuccess(res, file) {
        this.shareFileLoading = false
        if (res.code === 101) {
          const fileUrl = res.data[0]
          this.importEntity.fileName = file.name
          this.importEntity.fileUrl = fileUrl
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
          return false
        }
      },
      saveImportGoods() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            var data = {
              reportName: this.importEntity.fileName,
              reportUrl: this.importEntity.fileUrl,
              enterpriseId: this.getEnterpriseId(),
              supplierId: this.getSupplierId()
            }
            importGoods(data).then(response => {
              if (response.isError) return
              this.$message({
                message: response.msg,
                type: 'success'
              })
              if (response.code === 101) {
                this.handleDeleteFile()
                this.isImportGoodsSuccess = true
              }
            })
          }
        })
      },
      handleReportCenter(query) {
        jumpToReportCenter(this, query, true)
      }
    }
  }
</script>

<style lang="less" scoped>
  .user-avatar {
    width: 68px;
    height: 68px;
    display: block;
    padding: 1px;
  }

  .v-align-h {
    justify-content: space-between;
    display: flex;
    flex-direction: column;
  }
</style>
